package com.hsy.baoinbao.modules.common;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hsy.baoinbao.R;

/**
 * Created by MartinDKent on 2016/3/23.
 */
public class NumberAdjustor extends LinearLayout implements View.OnClickListener {
    private int min = 0;
    private int max = 100;

    public NumberAdjustor(Context context) {
        super(context);
        init(context);
    }

    public NumberAdjustor(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public NumberAdjustor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    ImageView increace;
    ImageView decreace;
    EditText data;

    private void init(Context context) {

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(100, 100);

        increace = new ImageView(context);
        decreace = new ImageView(context);

        increace.setLayoutParams(params);
        decreace.setLayoutParams(params);

        increace.setImageResource(R.mipmap.icon_add);
        decreace.setImageResource(R.mipmap.icon_minus);

        increace.setTag(0);
        decreace.setTag(1);

        increace.setOnClickListener(this);
        decreace.setOnClickListener(this);

        params = new ViewGroup.LayoutParams(100, 100);
        data = new EditText(context);
        data.setLayoutParams(params);
        data.setBackgroundResource(R.drawable.number_adjustor_bg);

        addView(increace);
        addView(data);
        addView(decreace);
    }

    @Override
    public final void onClick(View v) {
        int tag = (int) v.getTag();
        if (0 == tag) {
            setValue(getValue() + 1);
        } else if (1 == tag) {
            setValue(getValue() - 1);
        }
    }

    public final void setRange(int min, int max) {
        this.min = min;
        this.max = max;
        if (getValue() > max) {
            setValue(max);
        }
        if (getValue() < min) {
            setValue(min);
        }
    }

    public final int getValue() {
        if (null != data) {
            return Integer.parseInt(data.getText().toString());
        }
        return 0;
    }

    public final void setValue(int value) {
        if (null != data && value >= min && value <= max) {
            data.setText(String.valueOf(value));
        }
    }
}